package com.kaiyidiannao.activity.daydaycoupon;

import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.*;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.AnimationUtils;
import android.view.animation.TranslateAnimation;
import android.widget.*;
import com.baidu.location.BDLocation;
import com.huewu.pla.lib.internal.PLA_AdapterView;
import com.kaiyidiannao.activity.login_or_registered.LoginOrRegistered;
import com.kaiyidiannao.activity.tour.TourGatherPublishActivity;
import com.kaiyidiannao.activity.tour.TourLineDetailActivity;
import com.kaiyidiannao.activity.tour.TourSmallNotePublishActivity;
import com.kaiyidiannao.activity.user_detail.EditUserDetail;
import com.kaiyidiannao.adapter.*;
import com.kaiyidiannao.common.BaseActionBarActivity;
import com.kaiyidiannao.common.pulltorefresh_view.DragListView;
import com.kaiyidiannao.common.util.AppUtils;
import com.kaiyidiannao.common.util.BdMapLocationUitls;
import com.kaiyidiannao.data.DataCenter;
import com.kaiyidiannao.https.HttpUtils;
import com.kaiyidiannao.main.R;
import com.kaiyidiannao.model.bean.DaydayCouponBean;
import com.kaiyidiannao.model.bean.TourBean;
import com.kaiyidiannao.model.bean.UserBean;
import com.kaiyidiannao.model.req.model.*;
import com.kaiyidiannao.view.ActionBarView;
import com.kaiyidiannao.view.AutoTextView;
import com.kaiyidiannao.view.EditTextWithDel;
import com.taplinker.core.util.LogUtil;

import java.io.Serializable;
import java.util.*;

/**
 * Created by 大志 on 14-4-1.
 * 天天惠，凑对去 两个模块公用的列表展示
 * 观察者
 */
public class DdcListActivity extends BaseActionBarActivity implements Observer, View.OnClickListener {
    public static final int ID_TOUR_SMALL_NOTE = 54;//凑对去-微记
    public static final int ID_TOUR_GATHER = 53;//凑对去-召集
    public static final int ID_TOUR_LINE = 55;//凑对去-旅游线路

    //模块划分属性
    public static final int MODULE_DAY_DAY_COUPON = 1; //天天惠模块
    public static final int MODLUE_TOUR = 2;//凑对去-旅游线路模块
    private int module_type = MODULE_DAY_DAY_COUPON;
    private int view_id; //区分底部分类导航用(四个菜单)（二个菜单）
    private int current_click_btn = 0; //底部导航按钮中，当前被点击的按钮

    private ViewGroup listView;//DragListView和瀑布流listview
    private ProgressBar progressBar;
    private CheckBox checkbox_category;//展开分类的checkbox
    private View no_content_view;//没有数据的布局对象
    private AutoTextView mTextView02; //置顶滚动栏

    private BaseAdapter adapter;
    private ArrayList<?> targetList;//列表数据

    //请求数据参数
    private int catid;
    private int currentPage = DataCenter.LISTVIEW_DEFAULT_PAGE;
    private boolean isClose = true; //actionBar分类的是否关闭的标识码, ture 表示关闭
    private boolean sortFlag = false; //天天惠价格排序表示，false：降序，ture:升序
    private boolean sortIsOpen = false;//排序是否开启
    private boolean fareSortFlag = true;// 先点一下按费用由低到高 (1)，再点一下，又高到底(-1)
    private int order = -1;

    //最新分类样式
    private ListView categoryListview;
    private SimpleAdapter simpleAdapter;
    private List<Map<String, String>> data;
    private String[] categoryTextArrays = null; //分类数组的对应的文字

    //凑对去，地步滑动导航用菜单
    private LinearLayout menuContainer;
    private View menuBgVew;
    private int preSelectMenuIndex;

    //凑对去-->
    private ArrayList<UserBean> beans = DataCenter.userBeans;
    private ArrayList<UserBean> userBeans = DataCenter.userLogin;
    private static final String TAG = "DdcListActivity";

    //凑对去-微记搜索
    private int serachFlag = 0; //搜索框标示, 1:表示搜索框开启; 0:表示搜索按钮关闭
    private String searchKey = "";
    private EditTextWithDel search_with_del;
    private ImageButton search_confim_button; //商家搜索对应的连个组件
    private ImageButton backImageButton;//返回按钮

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.setContentView(R.layout.daydaycoupon_list_activity);

        module_type = getIntent().getIntExtra("module_type", MODULE_DAY_DAY_COUPON);
        selectModuleCatId(0, true);
        if (module_type == MODULE_DAY_DAY_COUPON) {
            DataCenter.rolling_current_module_id = DataCenter.moduleFlag.daydaycoupon;
            targetList = DataCenter.daydayCouponBeanList;
            findViewById(R.id.bottom_navi).setVisibility(View.GONE);
        } else {
            findViewById(R.id.bottom_navi).setVisibility(View.VISIBLE);
            targetList = DataCenter.tourList;
        }
        // 添加观察者
        DataCenter.getInstance().addObserver(this);

        findViews();
        //处理ActionBar
        findActionBar();

        DataCenter.rolling_tour_module_id = catid;
        // testBDLOcation();

        //最新分类
        initCategoryData();
        initCategoryView();
        //设置category默认文字

        showCurrentProgressView();
        if (module_type == MODULE_DAY_DAY_COUPON) {
            new GetDayDayCouponLIstTop(catid).execute();
            new GetDayDayCouponLIst(catid, currentPage).execute();
        } else if (module_type == MODLUE_TOUR) {
            new GetTourTop(catid).execute();
            if (catid == DataCenter.CATID_TOUR_GATHER) {
                actionBarView.setTitle("召集");
            }
            //new GetTourLIst(catid, currentPage).execute();
            menuContainer.getChildAt(0).performClick();// 默认点击第一个按钮，执行对应的请求
        }


        // 设置(底部四个按钮，或者二个按钮导航)默认被选择的组件id
        if (catid == ID_TOUR_LINE) {
            view_id = R.id.tour_menu_navi1;
        } else {
            view_id = R.id.tour_menu_navi2_1;
        }

        //处理ActionBar
        findActionBar();


        if (module_type == MODULE_DAY_DAY_COUPON) {
            actionBarView.setTitle("分类");
        } else {
            actionBarView.setTitle("召集");
        }

    }

    @Override
    public void onResume() {
        super.onResume();
    }


    @Override
    protected void onRestart() {
        if (module_type == MODULE_DAY_DAY_COUPON) {
            new GetDayDayCouponLIstTop(catid).execute();
            new GetDayDayCouponLIst(catid, currentPage).execute();
        } else if (module_type == MODLUE_TOUR) {
            //添加更新操作:
            switch (view_id) {
                case R.id.tour_menu_navi1://短途、按添加时间排序
                    new GetTourLIst(catid, currentPage).execute();
                    break;
                case R.id.tour_menu_navi2://长途、按添加时间排序
                    new GetTourLIst(catid, GetTourLIst.KIND_DEFAULT_LONG, currentPage).execute();
                    break;
                case R.id.tour_menu_navi3://按费用升序排列
                    new GetTourLIst(catid, GetTourLIst.ORDER_DEFAULT_COURSE, currentPage).execute();
                    break;
                case R.id.tour_menu_navi4://按人气降序排列
                    new GetTourLIst(catid, GetTourLIst.ORDER_DEFAULT_POPULARITY, currentPage).execute();
                    break;
                case R.id.tour_menu_navi2_1:
                    new GetTourGatherLIst(catid, currentPage, 1, DataCenter.currentAddress).execute();
                    break;
                case R.id.tour_menu_navi2_2:
                    new GetTourGatherLIst(catid, currentPage, DataCenter.currentAddress).execute();
                    break;
                default:
                    showToast("一个都没");
            }
        }
        super.onRestart();
    }

    public ViewGroup getListView() {
        return listView;
    }

    //===================================================底部动画start============================
    private void initBottomMneu() {
        findViewById(R.id.bottom_navi).setVisibility(View.VISIBLE);

        menuBgVew = findViewById(R.id.tour_menuBgVew);

        if (catid == ID_TOUR_LINE) {
            menuContainer = (LinearLayout) findViewById(R.id.tour_menuContainer_four);
            findViewById(R.id.tour_menuContainer_four).setVisibility(View.VISIBLE);
            findViewById(R.id.tour_menuContainer_two).setVisibility(View.GONE);
        } else if (catid == ID_TOUR_GATHER) {
            menuContainer = (LinearLayout) findViewById(R.id.tour_menuContainer_two);
            findViewById(R.id.tour_menuContainer_four).setVisibility(View.GONE);
            findViewById(R.id.tour_menuContainer_two).setVisibility(View.VISIBLE);
        }


        for (int i = 0; i < menuContainer.getChildCount(); i++) {
            TextView menuTextView = (TextView) menuContainer.getChildAt(i);
            final int j = i;
            menuTextView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    menuOnClick(v);
                    current_click_btn = j;
                }
            });
        }


        //默认选中第一个
        preSelectMenuIndex = 0;


        // 该事件是在组件被加载到界面，并且可以获取到大小的时候调用
        menuContainer.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {

            @Override
            public void onGlobalLayout() {
                // Ensure you call it only once :
                menuContainer.getViewTreeObserver().removeGlobalOnLayoutListener(this);

                // Here you can get the size :)

                TextView firstMenuTextView = (TextView) menuContainer.getChildAt(0);

                Log.d(TAG, "first menu width " + firstMenuTextView.getWidth());

                //menuBgVew.setWidth(firstMenuTextView.getWidth());

                RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) menuBgVew.getLayoutParams();
                layoutParams.width = firstMenuTextView.getWidth();
                menuBgVew.setLayoutParams(layoutParams);
            }
        });


    }

    private void menuOnClick(View view) {
        currentPage = DataCenter.LISTVIEW_DEFAULT_PAGE;
        targetList.clear();

        for (int i = 0; i < menuContainer.getChildCount(); i++) {
            TextView menuTextView = (TextView) menuContainer.getChildAt(i);
            menuTextView.setTextColor(getResources().getColor(R.color.font_black));
        }
        ((TextView) view).setTextColor(getResources().getColor(R.color.title_detail_color));

        view_id = view.getId();
        //添加更新操作: (底部四种导航的)
        executeTourLineListRequest(true);

        Log.d(TAG, "view width " + view.getWidth());

        int currentSelectMenuIndex = menuContainer.indexOfChild(view);


//        TranslateAnimation animation = new TranslateAnimation(Animation.RELATIVE_TO_SELF, preSelectMenuIndex,
//                Animation.RELATIVE_TO_SELF, currentSelectMenuIndex,
//                Animation.RELATIVE_TO_SELF, 0f,
//                Animation.RELATIVE_TO_SELF, 0f);

        float preOffset = 0;
        for (int i = 0; i < preSelectMenuIndex; i++) {
            preOffset += menuContainer.getChildAt(i).getWidth();
        }


        float newOffset = 0;
        for (int i = 0; i < currentSelectMenuIndex; i++) {
            newOffset += menuContainer.getChildAt(i).getWidth();
        }

        TranslateAnimation translateAnimation = new TranslateAnimation(preOffset, newOffset, 0, 0);
        translateAnimation.setDuration(300);
//        translateAnimation.setFillAfter(true);
//        menuBgVew.startAnimation(animation);

        int oldWidth = menuBgVew.getWidth();
        int newWidth = view.getWidth();

        float oldScale = ((float) menuContainer.getChildAt(preSelectMenuIndex).getWidth()) / ((float) menuBgVew.getWidth());
        float newScale = ((float) menuContainer.getChildAt(currentSelectMenuIndex).getWidth()) / ((float) menuBgVew.getWidth());

        Log.d(TAG, "oldScale " + oldScale);
        Log.d(TAG, "newScale " + newScale);

        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) menuBgVew.getLayoutParams();
        layoutParams.width = newWidth;
        menuBgVew.setLayoutParams(layoutParams);


        AnimationSet animationSet = new AnimationSet(true);
        animationSet.addAnimation(translateAnimation);
        //animationSet.addAnimation(scaleAnimation);

        animationSet.setFillAfter(true);
        menuBgVew.startAnimation(animationSet);

        preSelectMenuIndex = currentSelectMenuIndex;

    } //===================================================底部动画END============================

    /**
     * @param isDisplayProgress
     */
    private void executeTourLineListRequest(boolean isDisplayProgress) {
        if (isDisplayProgress) {
            showCurrentProgressView();
        }
        //添加更新操作:
        switch (view_id) {
            case R.id.tour_menu_navi1://短途、按添加时间排序
                new GetTourLIst(catid, currentPage).execute();
                break;
            case R.id.tour_menu_navi2://长途、按添加时间排序
                new GetTourLIst(catid, GetTourLIst.KIND_DEFAULT_LONG, currentPage).execute();
                break;
            case R.id.tour_menu_navi3://按费用升序排列
                if (fareSortFlag) {
                    Log.d("xxx", "ORDER_DEFAULT_COURSE");
                    new GetTourLIst(catid, GetTourLIst.ORDER_DEFAULT_COURSE, currentPage).execute();
                } else {
                    //降序
                    Log.d("xxx", "ORDER_DEFAULT_DIS降序");
                    new GetTourLIst(catid, GetTourLIst.ORDER_DEFAULT_DIS, currentPage).execute();
                }
                fareSortFlag = ! fareSortFlag;
                break;
            case R.id.tour_menu_navi4://按人气降序排列
                new GetTourLIst(catid, GetTourLIst.ORDER_DEFAULT_POPULARITY, currentPage).execute();
                break;
            case R.id.tour_menu_navi2_1:
                new GetTourGatherLIst(catid, currentPage, 1, DataCenter.currentAddress).execute();
                break;
            case R.id.tour_menu_navi2_2:
                new GetTourGatherLIst(catid, currentPage, DataCenter.currentAddress).execute();
                break;
            default:
                showToast("一个都没");
        }

    }

    //列表为空的时候执行
    private void initList() {
        if (targetList == null || targetList.size() <= 0) {
            progressBar.setVisibility(View.VISIBLE);
        }
    }


    private void testBDLOcation() {
        final BdMapLocationUitls locationUitls = new BdMapLocationUitls();
        locationUitls.startLocation();
        Toast.makeText(DdcListActivity.this, "location:start", Toast.LENGTH_LONG).show();
        locationUitls.setListenter(new BdMapLocationUitls.LocationListenter() {

            @Override
            public void onReceiveLocation(BDLocation bdLocation) {
                Toast.makeText(DdcListActivity.this, "location:recive", Toast.LENGTH_LONG).show();
                if (bdLocation != null) {
                    String curAddress = bdLocation.getAddrStr(); // 地理位置
                    if (curAddress != null && !curAddress.trim().isEmpty()) {
                        Toast.makeText(DdcListActivity.this, "location:" + curAddress, Toast.LENGTH_LONG).show();
                        Log.d("testBDLOcation", curAddress);
                        locationUitls.stopLocation();
                    }
                }
            }
        });

    }

    private void findActionBar() {
        actionBarView = (ActionBarView) findViewById(R.id.actionbar);
        actionBarView.setTitle("分类");
        actionBarView.setTitleOnClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isClose = !isClose;
                if (isClose) {
                    closeTopBar();
                } else { //开启分类条
                    openTopBar();
                }
            }
        });
        actionBarView.setTitleIconIsUp(false);


        checkbox_category = actionBarView.checkBox;
        checkbox_category.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isShownTopBar()) {
                    closeTopBar();
                } else {
                    openTopBar();
                }
                checkbox_category.setChecked(isShownTopBar());
            }
        });

        if (module_type == MODULE_DAY_DAY_COUPON) {
            findActionBar_daydaycoupon();
        } else {
            if (catid == DataCenter.CATID_TOUR_GATHER) {
                findActionBar_tour_gather();
            } else if (catid == DataCenter.CATID_TOUR_SMALL_NOTE) {
                findActionBar_tour_small_note();
            } else {
                findActionBar_tour_line();
            }
        }
    }

    private void findActionBar_daydaycoupon() {
        actionBarView.button_right_icon1.setVisibility(View.VISIBLE); //购物车按钮
        actionBarView.button_right_icon1.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.daydaycoupon_shopping_car));
        actionBarView.button_right_icon1.setOnClickListener(this);

        actionBarView.button_right_icon2.setVisibility(View.VISIBLE);//排序按钮
        actionBarView.button_right_icon2.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.daydaycoupon_sort_up));
        actionBarView.button_right_icon2.setOnClickListener(this);
    }

    //凑对去,召集 - actionBar
    private void findActionBar_tour_gather() {
        actionBarView.button_right_icon2.setVisibility(View.VISIBLE);
        actionBarView.button_right_icon2.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.publish));
        actionBarView.button_right_icon2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (userBeans.size() == 0) {
                    Intent intent = new Intent(DdcListActivity.this, LoginOrRegistered.class);
                    //intent.putExtra("ClassName", DdcListActivity.class.getName());
                    startActivity(intent);
                    Toast.makeText(DdcListActivity.this, "请先登录", Toast.LENGTH_SHORT).show();
                   // finish();
                } else if (beans.get(0).getUsername() == null || beans.get(0).getUsername().equals("")) {
                    Intent intent = new Intent(DdcListActivity.this, EditUserDetail.class);
                   // intent.putExtra("ClassName", DdcListActivity.class.getName());
                    startActivity(intent);
                    Toast.makeText(DdcListActivity.this, "请完善您的个人信息", Toast.LENGTH_SHORT).show();
                    //finish();
                } else {
                    android.util.Log.d("username", beans.get(0).getUserid() + "----------");
                    //  上传商品
                    Intent intent = new Intent(DdcListActivity.this, TourGatherPublishActivity.class);
                    startActivity(intent);
                }
            }
        });

        actionBarView.button_right_icon1.setVisibility(View.GONE);
    }

    //凑对去,旅游线路 actionBar
    private void findActionBar_tour_line() {
        actionBarView.button_right_icon1.setVisibility(View.GONE);
        actionBarView.button_right_icon2.setVisibility(View.GONE);
    }

    //凑对去-微记
    private void findActionBar_tour_small_note() {
        // 发布
        actionBarView.button_right_icon2.setVisibility(View.VISIBLE);
        actionBarView.button_right_icon2.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.publish));
        actionBarView.button_right_icon2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (userBeans.size() == 0) {
                    Intent intent = new Intent(DdcListActivity.this, LoginOrRegistered.class);
                    //intent.putExtra("ClassName", DdcListActivity.class.getName());
                    startActivity(intent);
                    Toast.makeText(DdcListActivity.this, "请先登录", Toast.LENGTH_SHORT).show();
                    //finish();
                } else if (beans.get(0).getUsername() == null || beans.get(0).getUsername().equals("")) {
                    Intent intent = new Intent(DdcListActivity.this, EditUserDetail.class);
                   // intent.putExtra("ClassName", DdcListActivity.class.getName());
                    startActivity(intent);
                    Toast.makeText(DdcListActivity.this, "请完善您的个人信息", Toast.LENGTH_SHORT).show();
                   // finish();
                } else {
                    android.util.Log.d("username", beans.get(0).getUserid() + "----------");
                    //  上传商品
                    Intent intent = new Intent(DdcListActivity.this, TourSmallNotePublishActivity.class);
                    startActivity(intent);
                }
            }
        });

        // 微记搜索
        actionBarView.button_right_icon1.setVisibility(View.VISIBLE);
        actionBarView.button_right_icon1.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.food_search));
        actionBarView.button_right_icon1.setOnClickListener(this);
    }

    private void findViews() {
        no_content_view = findViewById(R.id.no_content_view);

        reloadListview();

        mTextView02 = (AutoTextView) findViewById(R.id.switcher02);
        progressBar = (ProgressBar) findViewById(R.id.daydaycoupon_inner_progress_bar);

        categoryListview = (ListView) findViewById(R.id.category_listview);

        // 顶部搜索
        search_with_del = (EditTextWithDel) findViewById(R.id.search_with_del);
        search_with_del.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                return false;
            }
        });
        search_confim_button = (ImageButton) findViewById(R.id.search_confim_button);
        search_confim_button.setOnClickListener(this);
        backImageButton = (ImageButton) findViewById(R.id.foodPalaceBack);
        backImageButton.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.actionbar_right_button_icon1:
                if (module_type == MODLUE_TOUR) {//凑对去(微记) - 点击搜索按钮
                    toSearch();
                } else if (module_type == MODULE_DAY_DAY_COUPON) { // 天天惠购物车按钮
                    toShoppingCar();
                }
                break;
            case R.id.search_confim_button: //搜索确定按钮
                searchKey = search_with_del.getText().toString();
//                if (TextUtils.isEmpty(searchKey.trim())) {
//                    showToast("搜索关键词不能为空");
//                    return;
//                }
                showCurrentProgressView();
                currentPage = DataCenter.LISTVIEW_DEFAULT_PAGE;
                targetList.clear();
//                if (!TextUtils.isEmpty(searchKey)) {
                AppUtils.hideKeyboard(DdcListActivity.this);
                new GetTourSamallNoteSearchLIst(searchKey, currentPage, DataCenter.CATID_TOUR_SMALL_NOTE).execute();
//                }
                break;
            case R.id.actionbar_right_button_icon2:
                // 天天惠排序
                sortIsOpen = true;
                if (sortFlag) { // true:升序
                    sortFlag = false;
                    order = 0;
                    actionBarView.button_right_icon2.setImageResource(R.drawable.daydaycoupon_sort_down);
                } else {// 降序
                    order = 1;
                    sortFlag = true;
                    actionBarView.button_right_icon2.setImageResource(R.drawable.daydaycoupon_sort_up);
                }
                showCurrentProgressView();
                currentPage = DataCenter.LISTVIEW_DEFAULT_PAGE;
                new GetDayDayCouponLIst(catid, currentPage, order).execute();
                break;
            case R.id.foodPalaceBack: //搜索框的返回按钮
                closeSearch();
                serachFlag = 0;
                currentPage = DataCenter.LISTVIEW_DEFAULT_PAGE;
                break;
        }
    }

    /**
     * 开启顶部搜索框框
     */
    private void toSearch() {
        Log.d("touch", "touch me");
        findViewById(R.id.actionbar).setVisibility(View.GONE);
        TranslateAnimation anim = new TranslateAnimation(
                Animation.RELATIVE_TO_SELF, -1.0f,
                Animation.RELATIVE_TO_SELF, 0.0f,
                Animation.RELATIVE_TO_SELF, 0.0f,
                Animation.RELATIVE_TO_SELF, 0.0f);
        anim.setFillAfter(true);
        anim.setDuration(1000);
        findViewById(R.id.foodPalaceSearch).setVisibility(View.VISIBLE);
        findViewById(R.id.search_with_del).startAnimation(anim);
        serachFlag = 1;
    }

    /**
     * 关闭顶部搜索框
     */
    private void closeSearch() {
        TranslateAnimation anim = new TranslateAnimation(
                Animation.RELATIVE_TO_SELF, 0.0f,
                Animation.RELATIVE_TO_SELF, -2.0f,

                Animation.RELATIVE_TO_SELF, 0.0f,
                Animation.RELATIVE_TO_SELF, 0.0f);
        anim.setFillAfter(true);
        anim.setDuration(1000);
        anim.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                findViewById(R.id.actionbar).setVisibility(View.VISIBLE);
                findViewById(R.id.foodPalaceSearch).setVisibility(View.GONE);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        findViewById(R.id.search_with_del).startAnimation(anim);
    }

    private void toShoppingCar() {
        if (isLogin()) {
            startActivity(new Intent(DdcListActivity.this, DdcShoppingCarActivity.class));
        } else {
            startLoginOrRegistered();
        }
    }

    private void reloadListview() {

        findViewById(R.id.daydaycoupon_listview).setVisibility(View.GONE);
        findViewById(R.id.tour_listView_waterfull).setVisibility(View.GONE);
        findViewById(R.id.bottom_navi).setVisibility(View.GONE);


        switch (catid) {
            case ID_TOUR_LINE:
                adapter = new TourLineAdapter(this, targetList);
                //底部滑动导航菜单
                DataCenter.rolling_current_module_id = DataCenter.moduleFlag.tour_line;
                initBottomMneu();
                break;
            case ID_TOUR_SMALL_NOTE:
                DataCenter.rolling_current_module_id = DataCenter.moduleFlag.tour_line;
                adapter = new TourSmallNoteAdapter(this, targetList);
                break;
            case ID_TOUR_GATHER:
                DataCenter.rolling_current_module_id = DataCenter.moduleFlag.tour_line;
                adapter = new TourGatherAdapter(this, targetList);
                initBottomMneu();
                break;
            default:
                adapter = new DaydaycouponListAdapter(this, targetList);

        }
        adapter.notifyDataSetChanged();

        if (module_type == MODLUE_TOUR && (catid == ID_TOUR_GATHER || catid == ID_TOUR_SMALL_NOTE)) {
            initXLIstView(); //瀑布流用
        } else {
            initDragListview(); //下拉刷新的用
        }
    }

    //初始化瀑布流
    private void initXLIstView() {
        listView = (ViewGroup) findViewById(R.id.tour_listView_waterfull);
        listView.setVisibility(View.VISIBLE);

        ((com.kaiyidiannao.common.waterfall_view.XListView) listView).setPullLoadEnable(true);
        ((com.kaiyidiannao.common.waterfall_view.XListView) listView).setPullRefreshEnable(true);
        ((com.kaiyidiannao.common.waterfall_view.XListView) listView).setAdapter(adapter);
        // XListView监听
        ((com.kaiyidiannao.common.waterfall_view.XListView) listView).setXListViewListener(new com.kaiyidiannao.common.waterfall_view.XListView.IXListViewListener() {
            @Override
            public void onRefresh() {
                currentPage = DataCenter.LISTVIEW_DEFAULT_PAGE;
                if (catid == ID_TOUR_SMALL_NOTE) { //微記
                    if (serachFlag == 0) {
                        new GetTourLIst(catid, currentPage).execute();
                    } else { //搜索框开启
                        targetList.clear();
                        searchKey = search_with_del.getText().toString();
                        new GetTourSamallNoteSearchLIst(searchKey, currentPage,DataCenter.CATID_TOUR_SMALL_NOTE).execute();
                    }
                } else if (catid == ID_TOUR_GATHER) {//召集
                    executeTourLineListRequest(false);
                }
            }

            @Override
            public void onLoadMore() {

                if (catid == ID_TOUR_SMALL_NOTE) { //微記
                    if (serachFlag == 0) {
                        new GetTourLIst(catid, ++currentPage).execute();
                    } else { //搜索框开启
                        //showCurrentProgressView();
                        searchKey = search_with_del.getText().toString();
                        new GetTourSamallNoteSearchLIst(searchKey, ++currentPage, DataCenter.CATID_TOUR_SMALL_NOTE).execute();
//                    if (!TextUtils.isEmpty(searchKey)) {
//                        new GetTourSamallNoteSearchLIst(searchKey, ++currentPage).execute();
//                    } else {
//                        showToast("搜索关键词不能为空");
//                        ((XListView) listView).stopLoadMore();
//                    }
                    }
                } else if (catid == ID_TOUR_GATHER) {//召集
                    switch (view_id) {
                        case R.id.tour_menu_navi2_1:
                            new GetTourGatherLIst(catid, ++currentPage, 1, DataCenter.currentAddress).execute();
                            break;
                        case R.id.tour_menu_navi2_2:
                            new GetTourGatherLIst(catid, ++currentPage, DataCenter.currentAddress).execute();
                            break;
                    }
                }


            }
        });
        ((com.kaiyidiannao.common.waterfall_view.XListView) listView).setOnItemClickListener(new PLA_AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(PLA_AdapterView<?> parent, View view, int position, long id) {
                Bundle bundleData = new Bundle();
                if (position - 1 < 0) {
                    return;
                }
                bundleData.putSerializable("bean", (Serializable) targetList.get(position - 1));
                bundleData.putInt("catid", catid);

                Class<?> classz = null;
                classz = TourLineDetailActivity.class;
                String itemid = DataCenter.tourList.get(position - 1).getItemid();
                bundleData.putString("itemid", itemid);

                DataCenter.gather_position = position-1;
                DataCenter.PAGE = (position-1)/10+1;
                currentPage = (position-1)/10+1;
                Intent intent = new Intent(DdcListActivity.this, classz);
                intent.putExtras(bundleData);
                startActivity(intent);
            }
        });
    }


    private void initDragListview() {
        listView = (DragListView) findViewById(R.id.daydaycoupon_listview);
        listView.setVisibility(View.VISIBLE);

        ((ListView) listView).setAdapter(adapter);
        ((ListView) listView).setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Bundle bundleData = new Bundle();
                bundleData.putSerializable("bean", (Serializable) targetList.get(position - 1));
                bundleData.putInt("catid", catid);
                Class<?> classz = null;
                switch (catid) {
                    case ID_TOUR_LINE://凑对去详情页面
                        classz = TourLineDetailActivity.class;
                        String itemid = DataCenter.tourList.get(position - 1).getItemid();
                        bundleData.putString("itemid", itemid);
                        break;
                    default://天天慧去详情页面
                        String itemid1 = DataCenter.daydayCouponBeanList.get(position - 1).getItemid();
                        bundleData.putString("itemid", itemid1);
                        classz = DdcDetailActivity.class;
                        DataCenter.day_position = position-1;
                        DataCenter.PAGE = (position-1)/10+1;
                        currentPage = (position-1)/10+1;
                }
                Intent intent = new Intent(DdcListActivity.this, classz);
                intent.putExtras(bundleData);
                startActivity(intent);
            }
        });
        ((DragListView) listView).setOnRefreshListener(new DragListView.OnRefreshLoadingMoreListener() {
            @Override
            public void onRefresh() {
                currentPage = DataCenter.LISTVIEW_DEFAULT_PAGE;
                if (module_type == ID_TOUR_LINE) {
                    executeTourLineListRequest(false);//底部的四种导航
                } else {
                    if (sortIsOpen) {
                        new GetDayDayCouponLIst(catid, DataCenter.LISTVIEW_DEFAULT_PAGE, order).execute();
                    } else {
                        new GetDayDayCouponLIst(catid, DataCenter.LISTVIEW_DEFAULT_PAGE).execute();
                    }
                }
            }

            @Override
            public void onLoadMore() {

                currentPage = currentPage + 1;

                if (catid == ID_TOUR_LINE) {
                    executeTourLineListRequest(false);//底部的四种导航
                } else {
                    if (sortIsOpen) {
                        new GetDayDayCouponLIst(catid, currentPage,order).execute();
                    } else {
                        new GetDayDayCouponLIst(catid, currentPage).execute();
                    }
                }
            }
        });

    }

    @Override
    public void onBackPressed() {
        if (adapter instanceof ImageLoaderBaseAdapter) {
            ((ImageLoaderBaseAdapter) adapter).clearDisplayImages();
        }
        super.onBackPressed();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        LogUtil.d(DataCenter.LOG_INFO, DdcListActivity.class.getSimpleName() + ".onDestroy");
        DataCenter.daydayCouponTopBeansList.clear();
        DataCenter.tourTopList.clear();
        //删除观察者
        DataCenter.getInstance().deleteObserver(this);
    }

    @Override
    public void update(Observable observable, Object data) {
        DataCenter.flag flag = (DataCenter.flag) data;
        if( listView instanceof DragListView){
            ((DragListView) listView).onRefreshComplete();
            ((DragListView) listView).onLoadMoreComplete(false);
        }else if(listView instanceof DragListView ){
            ((com.kaiyidiannao.common.waterfall_view.XListView) listView).stopRefresh();
            ((com.kaiyidiannao.common.waterfall_view.XListView) listView).stopLoadMore();
        }
        if (!HttpUtils.isConnected()) {
            progressBar.setVisibility(View.GONE);
            no_content_view.setVisibility(View.VISIBLE);
        }

        if (listView instanceof DragListView) {//下拉刷新的用
            ((DragListView) listView).onRefreshComplete();
            ((DragListView) listView).onLoadMoreComplete(false);
        } else {//瀑布流用
            ((com.kaiyidiannao.common.waterfall_view.XListView) listView).stopRefresh();
            ((com.kaiyidiannao.common.waterfall_view.XListView) listView).stopLoadMore();
        }

        if (flag == DataCenter.flag.GET_DAY_DAY_COUPON_LIST_FAILED) {
            if (targetList.size() < 1) {
                showCurrentEmptyMsgView(getText(R.string.listview_msg_error)); //请求失败，请重试
            } else {
                showCurrentDataView();
            }
            Log.d(DataCenter.LOG_ERROR, " DdcListActivity.update() -> FAILED");
        }

        if (flag == DataCenter.flag.GET_DAY_DAY_COUPON_LIST_SUCCESS) { //列表数据
            Log.d(DataCenter.LOG_INFO, " DdcListActivity.update() -> SUCCESS");
            if ((targetList == null || targetList.size() < 1)) {
                showCurrentEmptyMsgView(null); //请求成功，但是空数据
            } else {
                showCurrentDataView();
            }
        }

        if (flag == DataCenter.flag.GET_DAY_DAY_COUPON_LIST_TOP_SUCCESS) { // 置顶滚动栏数据
            if (module_type == MODULE_DAY_DAY_COUPON) {
                ArrayList<DaydayCouponBean> topBeanList = DataCenter.daydayCouponTopBeansList;
                mTextView02.setData3(topBeanList);
                mTextView02.startRolling();
            } else {
                ArrayList<TourBean> topBeanList = DataCenter.tourTopList;
                mTextView02.setData3(topBeanList);
                mTextView02.startRolling();
            }
        }

        if (flag == DataCenter.flag.GET_DAY_DAY_COUPON_LIST_NO_MORE_DATA) {
            currentPage--;
//            showToast("没有数据了");
        }

        if (flag == DataCenter.flag.COMMON_REQUEST_FAILED) {
            closeProgressDialog();
            if ((targetList == null || targetList.size() < 1)) {
                showCurrentEmptyMsgView(null); //请求成功，但是空数据
            } else {
                showCurrentDataView();
            }
        }

        adapter.notifyDataSetChanged();
    }


    protected void openTopBar() {
        actionBarView.setTitleIconIsUp(true);
        categoryListview.setVisibility(View.VISIBLE);
        categoryListview.setAnimation(AnimationUtils.loadAnimation(this, R.anim.top_bar_in));
        simpleAdapter.notifyDataSetChanged();
    }

    @Override
    protected void closeTopBar() {

        actionBarView.setTitleIconIsUp(false);

        categoryListview.setAnimation(AnimationUtils.loadAnimation(this, R.anim.top_bar_out));
        categoryListview.setVisibility(View.GONE);
    }


    @Override
    protected boolean isShownTopBar() {
        return categoryListview.getVisibility() == View.VISIBLE;
    }

    private void initCategoryData() {
        data = new ArrayList<Map<String, String>>();

        TreeMap<String, String> map = null;

        if (module_type == MODULE_DAY_DAY_COUPON) {
            categoryTextArrays = getResources().getStringArray(R.array.daydaycouponCategory);
        } else {
            categoryTextArrays = getResources().getStringArray(R.array.tourCategory);
        }


        for (int i = 0; i < categoryTextArrays.length; ++i) {
            map = new TreeMap<String, String>();
            if (module_type == MODLUE_TOUR) {
                if (i == 0) {
                    map.put("img", "" + DataCenter.commmon_category_img[0]);
                } else {
                    map.put("img", "" + DataCenter.commmon_category_img[1]);
                }
            } else {
                map.put("img", "" + DataCenter.getDaydaycoupon_category_img[i]);
            }
            map.put("title", categoryTextArrays[i] + "...");
            data.add(map);
        }
    }

    private void initCategoryView() {
        categoryListview = (ListView) findViewById(R.id.category_listview);

        String[] from = new String[]{"img", "title"};
        int[] to = new int[]{R.id.category_icon, R.id.category_title};
        simpleAdapter = new SimpleAdapter(this, data, R.layout.category_listview_item, from, to);
        categoryListview.setAdapter(simpleAdapter);
        categoryListview.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                view.setPressed(true);
                //initCategoryView(); //刷新顶部分类

                DataCenter.daydayCouponBeanList.clear();
                DataCenter.daydayCouponTopBeansList.clear();
                DataCenter.tourList.clear();
                DataCenter.tourTopList.clear();
                currentPage = 1;

                isClose = true;
                closeTopBar();
                //设置category默认文字
                actionBarView.setTitle(categoryTextArrays[i]);
                selectModuleCatId(i, false);
                reloadListview(); //重新初始化listview

                if (catid == ID_TOUR_LINE || catid == ID_TOUR_GATHER) {
                    menuContainer.getChildAt(0).performClick();
                    if (catid == ID_TOUR_LINE) {
                        view_id = R.id.tour_menu_navi1;
                    } else {
                        view_id = R.id.tour_menu_navi2_1;
                    }
                }

                showCurrentProgressView();
                if (module_type == MODULE_DAY_DAY_COUPON) {
                    new GetDayDayCouponLIstTop(catid).execute();
                    new GetDayDayCouponLIst(catid, currentPage).execute();
                } else {//凑对去模块
                    new GetTourTop(catid).execute();
                    if (catid == ID_TOUR_GATHER) {
                        new GetTourGatherLIst(catid, currentPage, DataCenter.currentAddress).execute();
                    } else {
                        new GetTourLIst(catid, currentPage).execute();
                    }

                    //选择actionBar
                    if (module_type == MODLUE_TOUR) {
                        switch (catid) {
                            case ID_TOUR_LINE:
                                findActionBar_tour_line();
                                break;
                            case ID_TOUR_GATHER:
                                findActionBar_tour_gather();
                                break;
                            case ID_TOUR_SMALL_NOTE:
                                findActionBar_tour_small_note();
                                break;
                        }
                        DataCenter.rolling_tour_module_id = catid;
                    }
                }
            }
        });


    }

    /**
     * 选择模块类别 catid
     * @param i
     * @param isFirst 是否第一次进入界面
     */
    private void selectModuleCatId(int i, boolean isFirst) {
        switch (module_type) {
            case MODULE_DAY_DAY_COUPON:
                catid = DataCenter.daydaycoupon_category_id[i];
                break;
            case MODLUE_TOUR:
                catid = DataCenter.tour_category_id[i];
                if (isFirst) { //第一进入界面，把默认变成召集
                    catid = DataCenter.CATID_TOUR_GATHER;
                }
                break;
        }
        DataCenter.rolling_tour_module_id = catid;
    }

    /**
     * 显示列表数据
     */
    private void showCurrentDataView() {
        listView.setVisibility(View.VISIBLE);
        no_content_view.setVisibility(View.GONE);
        progressBar.setVisibility(View.GONE);
    }

    /**
     * 正在加载，隐藏列表
     */
    private void showCurrentProgressView() {
        listView.setVisibility(View.GONE);
        no_content_view.setVisibility(View.GONE);
        progressBar.setVisibility(View.VISIBLE);
    }

    /**
     * 提示没有数据或者请求失败
     */
    private void showCurrentEmptyMsgView(CharSequence resStr) {
        listView.setVisibility(View.GONE);
        if (TextUtils.isEmpty(resStr)) {
            resStr = getText(R.string.listview_msg_empty);
        }
        ((TextView) no_content_view.findViewById(R.id.notice_msg_tv)).setText(resStr);
        no_content_view.setVisibility(View.VISIBLE);
        progressBar.setVisibility(View.GONE);
    }


    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK || event.getKeyCode() == KeyEvent.KEYCODE_MENU) {
            if (isShownTopBar()) { // 顶部分类
                actionBarView.checkBox.setChecked(false);
                isClose = true;
                closeTopBar();
                return false;
            }


            if (serachFlag == 1) { // 若果搜索框开启状态
                closeSearch();
                currentPage = DataCenter.LISTVIEW_DEFAULT_PAGE;
                serachFlag = 0;
                return false;
            }
        }
        return super.dispatchKeyEvent(event);
    }
}